package com.tang.filter;

import com.tang.config.JwtAuthorizationConfig;
import com.tang.domian.Token;
import com.tang.utils.Base64SerializationUtils;
import com.tang.utils.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @classname JwtTokenFilter
 * @description [  ]
 * @date 2021/5/1 15:49
 */
public class JwtTokenFilter extends AbstractDirectTokenFilter {

    private static final String Authorization = "Authorization";

    private JwtAuthorizationConfig jwtAuthorizationConfig;

    public JwtTokenFilter(JwtAuthorizationConfig jwtAuthorizationConfig) {
        this.jwtAuthorizationConfig = jwtAuthorizationConfig;
    }

    @Override
    protected void onUnSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    }

    @Override
    protected Authentication getAuthentication(String token) {
        UsernamePasswordAuthenticationToken authenticationToken = null;
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>(10);
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        try {
            Token tokenBean = JwtUtil.getToken(jwtAuthorizationConfig, token);
            Optional.ofNullable(tokenBean.getAuthorityCodes())
                    .ifPresent(item -> {
                        authorities.addAll(item.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
                    });
            // 构建 token
            authenticationToken = new UsernamePasswordAuthenticationToken(tokenBean.getUsername(),null,authorities);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("JwtTokenFilter过滤器执行结束...");
        return authenticationToken;
    }

    @Override
    protected String getHeaderName() {
        return Authorization;
    }
}